package com.kly.cashmall.module.profile.adapter;

import android.Manifest;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.google.firebase.analytics.FirebaseAnalytics;
import com.google.gson.JsonObject;
import com.kly.cashmall.AppApplication;
import com.kly.cashmall.R;
import com.kly.cashmall.baserx.RxManager;
import com.kly.cashmall.bean.AdvanceLivenessDetectionBean;
import com.kly.cashmall.bean.BankDetailBean;
import com.kly.cashmall.bean.ContactsBean;
import com.kly.cashmall.bean.GeneralInputParamsBean;
import com.kly.cashmall.bean.LivenessDetectionBean;
import com.kly.cashmall.bean.ProfileInfoBean;
import com.kly.cashmall.event.FirebaseAnalyticsEvent;
import com.kly.cashmall.popup.SelectListPopup;
import com.kly.cashmall.services.Network;
import com.kly.cashmall.services.Params;
import com.kly.cashmall.utils.function.CommonUtils;
import com.kly.cashmall.utils.system.ContactsUtils;
import com.kly.cashmall.utils.data.DateUtil;
import com.kly.cashmall.utils.data.DensityUtil;
import com.kly.cashmall.utils.system.PermissionUtils;
import com.kly.cashmall.utils.data.TextUtil;
import com.kly.cashmall.utils.function.ToastUtil;
import com.kly.cashmall.utils.ViewHolder;
import com.kly.cashmall.utils.aliyun.FileOssUpload;
import com.kly.cashmall.widget.GetText;
import com.kly.cashmall.widget.datepicker.DatePickerDialogUtil;
import com.kly.cashmall.widget.delay.DelayClickImageView;
import com.kly.cashmall.widget.delay.DelayClickTextView;
import com.kly.cashmall.widget.picker.PhotoPicker;
import com.kly.cashmall.widget.picker.TakeListener;
import com.yanzhenjie.permission.runtime.Permission;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import ai.advance.liveness.lib.Detector;
import ai.advance.liveness.lib.GuardianLivenessDetectionSDK;
import ai.advance.liveness.lib.LivenessResult;
import ai.advance.liveness.lib.Market;
import ai.advance.liveness.sdk.activity.LivenessActivity;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * @author 目前定义类型1~11，0为特殊类型分类标题
 */
public class GeneralInfoAdapter extends BaseAdapter {

    private static final String TAG = "InformationAdapter";

    private static final int REQUEST_CODE = 1001;
    private static final int KEY_TO_DETECT_REQUEST_CODE = 122;
    public static final int REQUEST_CODE_LIVENESS = 1002;
    private RxManager rxManager;
    private Activity context;
    private List<ListItemObj> itemList;

    private PhotoPicker mPhotoPicker;
    private int mPosition;

    private static class ListItemObj implements Serializable {
        public int type;
        public Object obj;
    }

    public GeneralInfoAdapter(Activity context) {
        this.context = context;
        rxManager = new RxManager();
    }

    public void setPersonInformationBean(ProfileInfoBean infoBean) {
        if (infoBean == null) {
            itemList = null;
            notifyDataSetChanged();
            return;
        }

        List<GeneralInputParamsBean> inputInfos = infoBean.getInputParams();

        List<ListItemObj> list = new ArrayList<>();

        for (GeneralInputParamsBean inputParamsBean : inputInfos) {
            ListItemObj listItemObj = new ListItemObj();
            listItemObj.obj = inputParamsBean;
            listItemObj.type = inputParamsBean.paramType;
            list.add(listItemObj);
        }

        this.itemList = list;
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        return itemList == null ? 0 : itemList.size();
    }

    @Override
    public int getViewTypeCount() {
        return 20;
    }

    @Override
    public int getItemViewType(int position) {
        return itemList.get(position).type;
    }

    @Override
    public Object getItem(int position) {
        return itemList.get(position).obj;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        switch (getItemViewType(position)) {
            case 0: {
                GeneralInputParamsBean inputParamsBean = (GeneralInputParamsBean) getItem(position);
                convertView = createTitleView(parent, inputParamsBean);
            }
            break;
            case 1: {
                GeneralInputParamsBean inputParamsBean = (GeneralInputParamsBean) getItem(position);
                convertView = createInputView(parent, inputParamsBean);
            }
            break;
            case 2: {
                GeneralInputParamsBean inputParamsBean = (GeneralInputParamsBean) getItem(position);
                convertView = createSelectorView(parent, inputParamsBean);
            }
            break;
            case 3: {
                GeneralInputParamsBean inputParamsBean = (GeneralInputParamsBean) getItem(position);
                convertView = createContactsView(parent, inputParamsBean);
            }
            break;
            case 4: {
                GeneralInputParamsBean inputParamsBean = (GeneralInputParamsBean) getItem(position);
                convertView = createDateView(parent, inputParamsBean);
            }
            break;
            case 5: {
                GeneralInputParamsBean inputParamsBean = (GeneralInputParamsBean) getItem(position);
                convertView = createInputAddressView(parent, inputParamsBean);

            }
            break;
            case 6: {
                GeneralInputParamsBean inputParamsBean = (GeneralInputParamsBean) getItem(position);
                GeneralInputParamsBean beforeInputParamsBean = null;
                convertView = createAddressView(parent, inputParamsBean, beforeInputParamsBean);
            }
            break;
            case 8: {
                GeneralInputParamsBean inputParamsBean = (GeneralInputParamsBean) getItem(position);
                convertView = createInputOTPView(parent, inputParamsBean);
            }
            break;
            case 9: {
                GeneralInputParamsBean inputParamsBean = (GeneralInputParamsBean) getItem(position);
                convertView = createUploadPhotoView(parent, inputParamsBean, position);
            }
            break;
            case 10: {
                GeneralInputParamsBean inputParamsBean = (GeneralInputParamsBean) getItem(position);
                convertView = createUploadFaceView(parent, inputParamsBean, position);
            }
            break;
            case 11: {
                GeneralInputParamsBean inputParamsBean = (GeneralInputParamsBean) getItem(position);
                convertView = createRadioView(parent, inputParamsBean);
            }
            break;
            default: {
                convertView = new LinearLayout(context);
            }
            break;
        }

        //隐藏下划线
        if (position >= getCount() - 1 || getItemViewType(position + 1) == 0) {
            View line = convertView.findViewById(R.id.item_line);
            if (line != null) {
                line.setVisibility(View.GONE);
            }
        }

        return convertView;
    }

    public void clearFocus() {
        View view = context.findViewById(android.R.id.content).findFocus();
        if (view != null) {
            view.clearFocus();
        }
    }

    /**
     * 标题 type=0
     */
    private View createTitleView(ViewGroup parent, GeneralInputParamsBean inputParamsBean) {
        View titleView = LayoutInflater.from(context).inflate(R.layout.item_general_info_title, parent, false);
        ((TextView) titleView.findViewById(R.id.title)).setText(inputParamsBean.paramName);
        return titleView;
    }

    /**
     * 文本框 type=1
     */
    private View createInputView(ViewGroup parent, final GeneralInputParamsBean inputParamsBean) {

        View view = LayoutInflater.from(context).inflate(R.layout.item_general_info_input, parent, false);
        ((TextView) view.findViewById(R.id.item_key)).setText(inputParamsBean.paramName);
        EditText editText = view.findViewById(R.id.item_value);
        editText.setText(inputParamsBean.inputValue);
        editText.setHint(inputParamsBean.inputDesc);
        editText.clearFocus();
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (editText.getText().toString().length() >= 11 && inputParamsBean.param.equalsIgnoreCase("ifsCode") && CommonUtils.isLower(editText.getText().toString())) {
                    getProfileIfsc(editText.getText().toString().trim());
                }

            }

            @Override
            public void afterTextChanged(Editable s) {
                inputParamsBean.inputValue = s.toString();
            }
        });
        return view;
    }

    /**
     * 下拉框 type=2
     */
    private View createSelectorView(ViewGroup parent, final GeneralInputParamsBean inputParamsBean) {
        View selectorView = LayoutInflater.from(context).inflate(R.layout.item_general_selector_view, parent, false);
        ((TextView) selectorView.findViewById(R.id.item_key)).setText(inputParamsBean.paramName);
        final TextView textView = selectorView.findViewById(R.id.item_value);
        textView.setHint(inputParamsBean.inputDesc);

        if (!TextUtils.isEmpty(inputParamsBean.inputValue)) {
            for (GeneralInputParamsBean.ParamsOptionBean paramsOptionBean : inputParamsBean.paramOptions) {
                if (inputParamsBean.inputValue.equalsIgnoreCase(paramsOptionBean.optionId)) {
                    textView.setText(paramsOptionBean.optionValue);
                }
            }
        }

        selectorView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clearFocus();
                int selectIndex = -1;
                if (!TextUtils.isEmpty(inputParamsBean.inputValue)) {
                    for (int i = 0; i < inputParamsBean.paramOptions.size(); i++) {
                        if (inputParamsBean.inputValue.equalsIgnoreCase(
                                inputParamsBean.paramOptions.get(i).optionId)) {
                            textView.setText(inputParamsBean.paramOptions.get(i).optionValue);
                            selectIndex = i;
                        }
                    }
                }

                new SelectListPopup(context).setTitle(inputParamsBean.paramName)
                        .setList(inputParamsBean.paramOptions, new GetText<GeneralInputParamsBean.ParamsOptionBean>() {
                            @Override
                            public String toText(GeneralInputParamsBean.ParamsOptionBean paramsOptionBean) {
                                return paramsOptionBean.optionValue;
                            }
                        }, selectIndex, new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                inputParamsBean.inputValue = inputParamsBean.paramOptions.get(position).optionId;
                                textView.setText(inputParamsBean.paramOptions.get(position).optionValue);
                            }
                        }).setPopupGravity(Gravity.CENTER).showPopupWindow();
            }
        });

        return selectorView;
    }

    /**
     * 通讯录选择 type=3
     */
    private View createContactsView(ViewGroup parent, final GeneralInputParamsBean inputParamsBean) {
        View contactsView = LayoutInflater.from(context).inflate(R.layout.item_contacts_view, parent, false);
        ((TextView) contactsView.findViewById(R.id.item_key)).setText(inputParamsBean.paramName);
        final TextView textView = contactsView.findViewById(R.id.item_value);
        textView.setHint(inputParamsBean.inputDesc);
        textView.setText(inputParamsBean.inputValue);
        contactsView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clearFocus();

                if (PermissionUtils.lacksPermission(context, Manifest.permission.READ_CONTACTS)) {
                    PermissionUtils.requestPermission(context, granted -> {
                        contactsGetListener = new ContactsGetListener() {
                            @Override
                            public void getContacts(ContactsBean contacts) {
                                //读取联系人返回参数固定
                                if (contacts.mobile != null) {
                                    inputParamsBean.inputValue = contacts.name + ":" + contacts.mobile;
                                    textView.setText(contacts.mobile);
                                }
                                contactsGetListener = null;
                            }
                        };
                        Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
//                        List<ResolveInfo> list = context.getPackageManager().queryIntentActivities(intent, 0);
//                        if (list.size() == 0) {
//                            ToastUtil.showAppToast(context.getString(R.string.contacts_list_empty));
//                            return;
//                        }
                        context.startActivityForResult(intent, REQUEST_CODE);
                    }, denied -> {
                        ToastUtil.showAppToast(context.getString(R.string.need_contacts_permission));
                    }, Manifest.permission.READ_CONTACTS);
                } else {
                    contactsGetListener = new ContactsGetListener() {
                        @Override
                        public void getContacts(ContactsBean contacts) {
                            //读取联系人返回参数固定
                            if (contacts.mobile != null) {
                                inputParamsBean.inputValue = contacts.name + ":" + contacts.mobile;
                                textView.setText(contacts.mobile);
                            }
                            contactsGetListener = null;
                        }
                    };
                    Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
//                    List<ResolveInfo> list = context.getPackageManager().queryIntentActivities(intent, 0);
//                    if (list.size() == 0) {
//                        ToastUtil.showAppToast(context.getString(R.string.contacts_list_empty));
//                        return;
//                    }
                    context.startActivityForResult(intent, REQUEST_CODE);

                }

            }

        });
        return contactsView;
    }

    /**
     * 日期选择 实为出生日期选择 type=4
     */
    private View createDateView(ViewGroup parent, final GeneralInputParamsBean inputParamsBean) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_date_view, parent, false);
        ((TextView) view.findViewById(R.id.item_key)).setText(inputParamsBean.paramName);

        final TextView textView = view.findViewById(R.id.item_value);
        textView.setText(inputParamsBean.inputValue);
        textView.setHint(inputParamsBean.inputDesc);

        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    Date date = new Date();
                    if (!TextUtils.isEmpty(inputParamsBean.inputValue)) {
                        date = DateUtil.strToDate(inputParamsBean.inputValue, "yyyy-MM-dd");
                    }
                    DatePickerDialogUtil.openDatePickerDialog(context,
                            new DatePickerDialogUtil.Options().setDate(date.getTime()).setMaxDate(Calendar.getInstance().getTime().getTime()),
                            new DatePickerDialogUtil.DatePickerDialogListener() {
                                @Override
                                public void onDateSet(DatePicker view, int year, int month, int day) {
                                    Calendar calendar = Calendar.getInstance();
                                    calendar.set(year, month, day);

                                    inputParamsBean.inputValue =
                                            DateUtil.parseDate(calendar.getTime().getTime(), "yyyy-MM-dd");
                                    textView.setText(inputParamsBean.inputValue);
                                }

                                @Override
                                public void onDismiss(DialogInterface dialog) {

                                }
                            });
                } catch (Exception e) {

                }
            }

        });
        return view;
    }

    /**
     * 地址输入 type=5
     */
    private View createInputAddressView(ViewGroup parent, final GeneralInputParamsBean inputParamsBean) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_general_info_address, parent, false);
        ((TextView) view.findViewById(R.id.item_key)).setText(inputParamsBean.paramName);
        EditText editText = view.findViewById(R.id.item_value);
        editText.setText(inputParamsBean.inputValue);
        editText.setHint(inputParamsBean.inputDesc);

        editText.clearFocus();
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                inputParamsBean.inputValue = s.toString();
            }
        });
        return view;
    }

    /**
     * 地址输入 可复制 type=6
     */
    private View createAddressView(ViewGroup parent, final GeneralInputParamsBean inputParamsBean, GeneralInputParamsBean beforeInputParamsBean) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_general_info_copy_address, parent, false);
        ((TextView) view.findViewById(R.id.item_key)).setText(inputParamsBean.paramName);
        final EditText editText = view.findViewById(R.id.item_value);
        DelayClickTextView copyTheAddress = view.findViewById(R.id.copy_the_address);
        editText.setText(inputParamsBean.inputValue);
        editText.setHint(inputParamsBean.inputDesc);
        for (int i = 0; i < itemList.size(); i++) {
            GeneralInputParamsBean paramsBean = (GeneralInputParamsBean) itemList.get(i).obj;
            if (paramsBean.param.equalsIgnoreCase(context.getString(R.string.addressId))) {
                beforeInputParamsBean = (GeneralInputParamsBean) itemList.get(i).obj;
            }
        }

        editText.clearFocus();
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                inputParamsBean.inputValue = s.toString();
            }
        });
        GeneralInputParamsBean finalBeforeInputParamsBean = beforeInputParamsBean;
        copyTheAddress.setOnClickListener(v -> {
            if (finalBeforeInputParamsBean != null) {
                if (!TextUtils.isEmpty(finalBeforeInputParamsBean.inputValue)) {
                    editText.setText(finalBeforeInputParamsBean.inputValue);
                } else {
                    ToastUtil.showAppToast("Please enter the" + finalBeforeInputParamsBean.paramName);
                }
            }
        });
        return view;
    }

    /**
     * 单独的输入框，不带标题文本 type=8
     */
    private View createInputOTPView(ViewGroup parent, final GeneralInputParamsBean inputParamsBean) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_general_in_simple_input, parent, false);
        EditText editText = view.findViewById(R.id.item_input);
        editText.setHint(inputParamsBean.inputDesc);
        editText.clearFocus();
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                inputParamsBean.inputValue = s.toString();
            }
        });
        return view;
    }


    /**
     * 拍照上传  type=9
     */
    private View createUploadPhotoView(ViewGroup parent, final GeneralInputParamsBean inputParamsBean, int position) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_upload_photo, parent, false);
        ViewHolder holder = ViewHolder.getHolder(view);
        holder.setText(R.id.item_key, inputParamsBean.paramName);
        DelayClickImageView mPhotoFront = holder.get(R.id.photo_front);
        if (TextUtils.isEmpty(inputParamsBean.inputValue)) {
            mPhotoFront.setImageResource(R.mipmap.ic_photo_sample);
        } else {
            holder.loadImage(context, R.id.photo_front, inputParamsBean.inputValue);
        }

        mPhotoPicker = PhotoPicker.create(context);

        mPhotoFront.setOnClickListener(view1 -> {
            if (PermissionUtils.lacksPermission(context, Permission.CAMERA) || PermissionUtils.lacksPermission(context, Permission.WRITE_EXTERNAL_STORAGE)) {
                PermissionUtils.requestPermission(context, data -> {
                    mPosition = position;
                    if (mPhotoPicker != null) {
                        mPhotoPicker.pickFromCamera();
                    }
                }, Permission.CAMERA, Permission.WRITE_EXTERNAL_STORAGE);
            } else {
                mPosition = position;
                if (mPhotoPicker != null) {
                    mPhotoPicker.pickFromCamera();
                }
            }

        });

        mPhotoPicker.setTakeListener(new TakeListener() {
            @Override
            public void onTakeSuccess(final String path) {
                upLoadImage(path);
            }

            @Override
            public void onTakeFailure(String msg) {
                ToastUtil.showToast(msg);
            }
        });
        return view;
    }

    /**
     * 活体检测  type=10
     */
    private View createUploadFaceView(ViewGroup parent, final GeneralInputParamsBean inputParamsBean, int position) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_upload_photo, parent, false);
        ViewHolder holder = ViewHolder.getHolder(view);
        holder.setText(R.id.item_key, inputParamsBean.paramName);
        DelayClickImageView mPhotoFront = holder.get(R.id.photo_front);
        if (TextUtils.isEmpty(inputParamsBean.inputValue)) {
            mPhotoFront.setImageResource(R.mipmap.ic_photo_sample);
        } else {
            holder.loadImage(context, R.id.photo_front, inputParamsBean.inputValue);
        }

        mPhotoFront.setOnClickListener(view1 -> {
            if (PermissionUtils.lacksPermission(context, Permission.CAMERA) || PermissionUtils.lacksPermission(context, Permission.WRITE_EXTERNAL_STORAGE)) {
                PermissionUtils.requestPermission(context, data -> {
                    mPosition = position;
                    getLiveness();
                }, Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE);
            } else {
                mPosition = position;
                getLiveness();
            }

        });
        return view;
    }

    private void getLiveness() {
        rxManager.add(Network.getApi().getFaceAdvanceLivenessLicense(new Params().buildPostBody()).subscribeOn(Schedulers.io()).observeOn
                (AndroidSchedulers.mainThread()).subscribe(new Consumer<LivenessDetectionBean>() {
            @Override
            public void accept(LivenessDetectionBean livenessDetectionBean) throws Exception {
                if (livenessDetectionBean.isUseAdvanceDetection()) {
                    GuardianLivenessDetectionSDK.init(AppApplication.getInstance(), Market.India);
                    String checkResult = GuardianLivenessDetectionSDK.setLicenseAndCheck(livenessDetectionBean.getLicense());
                    if ("SUCCESS".equals(checkResult)) {
                        // license 有效
                        FirebaseAnalytics.getInstance(AppApplication.getInstance()).logEvent(FirebaseAnalyticsEvent.Profile_Liveness_Success,new Bundle());
                        GuardianLivenessDetectionSDK.setActionSequence(false, Detector.DetectionType.POS_YAW, Detector.DetectionType.MOUTH, Detector.DetectionType.BLINK);
                        startLivenessActivity();
                    } else {
                        // license 不可用，过期/格式错误/appId未备案
                        FirebaseAnalytics.getInstance(AppApplication.getInstance()).logEvent(FirebaseAnalyticsEvent.Profile_Liveness_Fail,new Bundle());
                        ToastUtil.showAppToast(checkResult);
                    }
                } else {
                    mPhotoPicker = PhotoPicker.create(context);
                    mPhotoPicker.pickFromCamera();
                    mPhotoPicker.setTakeListener(new TakeListener() {
                        @Override
                        public void onTakeSuccess(final String path) {
                            upLoadImage(path);
                        }

                        @Override
                        public void onTakeFailure(String msg) {
                            ToastUtil.showToast(msg);
                        }
                    });
                }
            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {
            }
        }));
    }


    /**
     * 单选 type=11
     */
    private View createRadioView(ViewGroup parent, final GeneralInputParamsBean inputParamsBean) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_general_info_radio, parent, false);
        ((TextView) view.findViewById(R.id.item_key)).setText(inputParamsBean.paramName);
        RadioGroup radioGroup = view.findViewById(R.id.radio_group);
        for (int i = 0; i < inputParamsBean.getParamOptions().size(); i++) {
            RadioButton tempButton = new RadioButton(context);
            tempButton.setBackgroundColor(Color.WHITE);
            tempButton.setButtonDrawable(R.drawable.selector_choice_high_agree);
            tempButton.setPadding(DensityUtil.dip2px(10), DensityUtil.dip2px(5), 0, DensityUtil.dip2px(5));
            tempButton.setText(inputParamsBean.getParamOptions().get(i).optionValue);
            radioGroup.addView(tempButton, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            int finalI = i;
            tempButton.setOnCheckedChangeListener((compoundButton, b) -> {
                if (b) {
                    inputParamsBean.inputValue = inputParamsBean.paramOptions.get(finalI).optionId;
                }
            });
        }
        return view;
    }

    public void upLoadImage(final String path) {
//        LoadingDialog.showLoading(context);
        context.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                FileOssUpload.uploadFile(context, path, new FileOssUpload.UploadCallback<String>() {
                    @Override
                    public void success(String s) {
                        if (!TextUtil.isEmpty(s)) {
                            GeneralInputParamsBean inputParamsBean = (GeneralInputParamsBean) getItem(mPosition);
                            inputParamsBean.inputValue = s;
                            context.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
//                                    LoadingDialog.dismissLoading();
                                    notifyDataSetChanged();
                                }
                            });
                        } else {
                            ToastUtil.showToast(context.getResources().getString(R.string.upload_failed));
                        }
                    }

                    @Override
                    public void fail(String msg) {
                        ToastUtil.showToast(TextUtil.isEmpty(msg) ? context.getResources().getString(R.string.upload_failed) : msg);
                    }
                });
            }
        });

    }

    /**
     * 启动活体检测
     */
    private void startLivenessActivity() {
        Intent intent = new Intent(context, LivenessActivity.class);
        context.startActivityForResult(intent, REQUEST_CODE_LIVENESS);
    }

    /**
     * 获取银行卡名称
     *
     * @param code
     */
    public void getProfileIfsc(String code) {
        Params params = new Params();
        params.put("ifsccode", code);
        rxManager.add(Network.getApi().getProfileIfsc(params.buildPostBody()).subscribeOn(Schedulers.io()).observeOn
                (AndroidSchedulers.mainThread()).subscribe(new Consumer<BankDetailBean>() {
            @Override
            public void accept(BankDetailBean bean) throws Exception {
                for (int j = 0; j < itemList.size(); j++) {
                    GeneralInputParamsBean obj = (GeneralInputParamsBean) itemList.get(j).obj;
                    if (obj.param.equalsIgnoreCase("bankName")) {
                        obj.inputValue = bean.getBANK();
                        notifyDataSetChanged();
                    }
                }
            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {
            }
        }));
    }

    /**
     * 返回null表示信息不全
     */
    public @Nullable
    JsonObject getParams() {
        JsonObject params = new JsonObject();
        for (int i = 0; itemList != null && i < itemList.size(); i++) {
            if (itemList.get(i).obj instanceof GeneralInputParamsBean) {
                GeneralInputParamsBean bean = (GeneralInputParamsBean) itemList.get(i).obj;
                if (!TextUtils.isEmpty(bean.inputValue)) {
                    params.addProperty(bean.param, bean.inputValue);
                } else {
                    if (bean.required) {
                        ToastUtil.showToast(bean.paramName + " is Empty!");
                        Log.d(TAG, bean.param + "值为空！！！！");
                        //意思是信息不全
                        return null;
                    }
                }
            }
        }
        return params;
    }

    /**
     * 在对应的Activity.onActivityResult调用
     */
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK && data != null && data.getData() != null) {
            if (contactsGetListener != null) {
                ContactsBean contactsBean = ContactsUtils.parseContactsBean(context, data.getData());
                if (contactsBean != null) {
                    if (!TextUtils.isEmpty(contactsBean.name) && !TextUtils.isEmpty(contactsBean.mobile)) {
                        contactsGetListener.getContacts(contactsBean);
                    } else {
                        ToastUtil.showToast(context.getResources().getString(R.string.selection_failed));
                    }
                } else {
                    ToastUtil.showToast(context.getResources().getString(R.string.selection_failed));
                }
                contactsGetListener = null;
            }
        } else if (requestCode == REQUEST_CODE_LIVENESS) {
            if (LivenessResult.isSuccess()) {// 活体检测成功
                String livenessId = LivenessResult.getLivenessId();// 本次活体id
                Bitmap livenessBitmap = LivenessResult.getLivenessBitmap();// 本次活体图片
                Params params = new Params();
                params.put("livenessId",livenessId);
                rxManager.add(Network.getApi().getAdvanceLivenessDetection(params.buildPostBody()).subscribeOn(Schedulers.io()).observeOn
                        (AndroidSchedulers.mainThread()).subscribe(new Consumer<AdvanceLivenessDetectionBean>() {
                    @Override
                    public void accept(AdvanceLivenessDetectionBean bean) throws Exception {
                        if (bean.getPass()) {
                            if (!TextUtils.isEmpty(bean.getImageUrl())) {
                                GeneralInputParamsBean inputParamsBean = (GeneralInputParamsBean) getItem(mPosition);
                                inputParamsBean.inputValue = bean.getImageUrl();
                                context.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        notifyDataSetChanged();
                                    }
                                });
                                ToastUtil.showToast(context.getResources().getString(R.string.upload_success));
                            }
                        } else {
                            ToastUtil.showToast("Please try again");
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        ToastUtil.showAppToast(throwable.getMessage());
                    }
                }));
            } else {// 活体检测失败
                String errorCode = LivenessResult.getErrorCode();// 失败错误码
                String errorMsg = LivenessResult.getErrorMsg();// 失败原因
                ToastUtil.showToast(errorMsg);
            }
        } else {
            if (mPhotoPicker != null) {
                mPhotoPicker.handleActivityResult(requestCode, resultCode, data);
            }
        }
    }

    private ContactsGetListener contactsGetListener;

    public interface ContactsGetListener {

        void getContacts(ContactsBean contacts);
    }
}
